package com.oracle.lingshangejia.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.oracle.lingshangejia.Constant;
import com.oracle.lingshangejia.MyApp;
import com.oracle.lingshangejia.R;
import com.oracle.lingshangejia.adapter.ExpertVideoAdapter;
import com.oracle.lingshangejia.adapter.ExpertVideoTitleAdapter;
import com.oracle.lingshangejia.base.BaseActivity;
import com.oracle.lingshangejia.bean.DoctorVideoBean;
import com.oracle.lingshangejia.bean.ExpertVideoTitleBean;
import com.oracle.lingshangejia.utils.LastClickUtils;
import com.oracle.lingshangejia.utils.MyToast;
import com.oracle.lingshangejia.utils.OkHttpUtils;
import com.oracle.lingshangejia.utils.SpUtils;

import java.util.HashMap;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

//专家视频界面
public class ExpertVideoActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout re_back;
    private RecyclerView recyclerview_expert_video_title;
    private ExpertVideoTitleAdapter expertVideoTitleAdapter;
    private XRecyclerView recyclerview_expert_video;
    private ExpertVideoAdapter expertVideoAdapter;
    private ExpertVideoTitleBean titleBean;
    private String channelName = "channelid";
    private AgoraAPIOnlySignal mAgoraAPI;
    private final int REQUEST_CODE = 0x01;
    private String mMyAccount;
    private String mSubscriber;
    private DoctorVideoBean mDoctorVideoBean; //专家列表数据
    private int mTitleId; //科室

    @Override
    public int intiLayout() {
        return R.layout.activity_expert_video;
    }

    @Override
    public void initView() {
        showLoading();
        re_back=findViewById(R.id.re_back);
        re_back.setOnClickListener(this);
        recyclerview_expert_video_title=findViewById(R.id.recyclerview_expert_video_title);
        recyclerview_expert_video=findViewById(R.id.recyclerview_expert_video);
        mMyAccount= (String) SpUtils.get(ExpertVideoActivity.this,"s_phone","");
        initAgoraEngineAndJoinChannel();
    }

    /**
     * 获取科室列表
     */
    private void getNetTitleList() {
        HashMap<Object,Object> map = new HashMap<>();
        OkHttpUtils.getNetWork(this, Constant.baseurl+"online/ksList",map,handler);
    }
    /**
     * 医生列表
     */
    private void getNetDoctorList(int ksId){
        int ysid= (int) SpUtils.get(ExpertVideoActivity.this,"ysid",0);
        HashMap<Object,Object> map = new HashMap<>();
        map.put("ksId",ksId);
        map.put("userId",ysid);//当前登录用户id
        OkHttpUtils.getNetWork(this, Constant.baseurl+"online/sjysList",map,doctorhandler);
    }
    /**
     * 医生handler
     */
    private Handler doctorhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    dismissLoading();
                    String s= (String) msg.obj;
                    Gson gson=new Gson();
                    mDoctorVideoBean = gson.fromJson(s,DoctorVideoBean.class);
                    if (mDoctorVideoBean.getCode()==0) {
                        queryUserOnline();
                        setDoctorVideoList(mDoctorVideoBean);
                    }else{
                        Toast.makeText(ExpertVideoActivity.this, mDoctorVideoBean.getMsg(),Toast.LENGTH_SHORT).show();
                    }
                    recyclerview_expert_video.refreshComplete();
                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(ExpertVideoActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(ExpertVideoActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(ExpertVideoActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    //查询专家是否在线
    private void queryUserOnline(){
        for (DoctorVideoBean.DataBean dataBean: mDoctorVideoBean.getData()){
            mAgoraAPI.queryUserStatus(dataBean.getPhone());
        }
    }

    /**
     * 设置医生视频列表
     * @param doctorVideoBean
     */
    private void setDoctorVideoList(DoctorVideoBean doctorVideoBean) {
        expertVideoAdapter = new ExpertVideoAdapter(this,doctorVideoBean.getData());
        recyclerview_expert_video.setAdapter(expertVideoAdapter);
        expertVideoAdapter.setOnClickListener((v -> {
           // System.out.println("ppppppppp"+LastClickUtils.isLastClick(""));
            if (LastClickUtils.isLastClick("点击的太快了")){
                int position = (int) v.getTag();
                if (doctorVideoBean.getData().get(position).isOnline()){
                    mSubscriber=doctorVideoBean.getData().get(position).getPhone();
                    channelName = mMyAccount + mSubscriber;
                    mAgoraAPI.channelInviteUser(channelName,mSubscriber, 0);
                }else {
                    MyToast.show("用户已离线");
                }
            }

           // mAgoraAPI.queryUserStatus(doctorVideoBean.getData().get(position).getPhone());
        }));
    }

    /**
     * 获取科室列表handler
     */
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String s= (String) msg.obj;
                    Gson gson=new Gson();
                    titleBean=gson.fromJson(s,ExpertVideoTitleBean.class);
                    if(titleBean.getCode()==0){
                        setTitleListData(titleBean);
                        mTitleId = titleBean.getData().get(0).getId();
                        getNetDoctorList(titleBean.getData().get(0).getId());
                    }else{
                        Toast.makeText(ExpertVideoActivity.this,titleBean.getMsg(),Toast.LENGTH_SHORT).show();
                    }

                    break;
                case 2: //连接上服务器，错误
                    String error= (String) msg.obj;
                    Toast.makeText(ExpertVideoActivity.this,error,Toast.LENGTH_SHORT).show();
                    break;
                case 3:  //没有网络
                    Toast.makeText(ExpertVideoActivity.this,"网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                case 4: //没有连接上服务器
                    Toast.makeText(ExpertVideoActivity.this,"连接服务器失败",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 设置标签
     * @param titleBean
     */
    private void setTitleListData(ExpertVideoTitleBean titleBean) {
        expertVideoTitleAdapter = new ExpertVideoTitleAdapter(this,titleBean.getData());
        recyclerview_expert_video_title.setAdapter(expertVideoTitleAdapter);
        expertVideoTitleAdapter.setOnItemClickListener(new ExpertVideoTitleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (titleBean!=null) {
                    mTitleId = titleBean.getData().get(position).getId();
                    getNetDoctorList(titleBean.getData().get(position).getId());
                }
            }
        });
    }

    @Override
    public void initData() {
        getNetTitleList();
        recyclerview_expert_video_title.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        recyclerview_expert_video.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recyclerview_expert_video.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

               getNetDoctorList(mTitleId);

            }

            @Override
            public void onLoadMore() {

                recyclerview_expert_video.loadMoreComplete();
            }
        });


    }
    @Override
    public void onClick(View v) {

        switch (v.getId()){

            //返回键
            case R.id.re_back:

                finish();
                break;
        }
    }
    private void addCallback() {
        MyApp.the().getmAgoraAPI().callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLoginSuccess(int i, int i1) {
                Log.i(TAG, "onLoginSuccess " + i + "  " + i1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onLoginFailed(final int i) {
                Log.i(TAG, "onLoginFailed " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGIN_E_NET) {
                            //  ToastUtils.show(new WeakReference<Context>(LoginActivity.this), getString(R.string.str_msg_net_bad));
                        }
                    }
                });
            }


            @Override
            public void onError(String s, int i, String s1) {
                Log.i(TAG, "onError s:" + s + " s1:" + s1);
            }

        });



        if (mAgoraAPI == null) {
            return;
        }

        mAgoraAPI.callbackSet(new AgoraAPI.CallBack() {

            @Override
            public void onLogout(final int i) {
                Log.i(TAG, "onLogout  i = " + i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (i == IAgoraAPI.ECODE_LOGOUT_E_KICKED) { // other login the account
                            Toast.makeText(ExpertVideoActivity.this, "Other login account, you are logout.", Toast.LENGTH_SHORT).show();

                        } else if (i == IAgoraAPI.ECODE_LOGOUT_E_NET) { // net
                            Toast.makeText(ExpertVideoActivity.this, "Logout for Network can not be.", Toast.LENGTH_SHORT).show();

                        }
                        finish();
                    }
                });

            }

            @Override
            public void onLoginFailed(int i) {
                Log.i(TAG, "onLoginFailed  i = " + i);
            }

            ////收到呼叫邀请回调
         /*   @Override
            public void onInviteReceived(final String channelID, final String account, int uid, String s2) { //call out other remote receiver
                Log.i(TAG, "onInviteReceived  channelID = " + channelID + " account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    *//*    Intent intent = new Intent(ExpertVideoActivity.this, CallActivity.class);
                        intent.putExtra("account", mMyAccount);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("subscriber", account);
                        intent.putExtra("type", Constant.CALL_IN);
                        startActivityForResult(intent, REQUEST_CODE);*//*
                    }
                });
            }*/

               //专家端收到呼叫回调
            @Override
            public void onInviteReceivedByPeer(final String channelID, final String account, int uid) {//call out other local receiver
                Log.i(TAG, "onInviteReceivedByPeer  channelID = " + channelID + "  account = " + account);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(ExpertVideoActivity.this, CallActivity.class);
                        intent.putExtra("account", mMyAccount);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("subscriber", account);
                        intent.putExtra("type", Constant.CALL_OUT);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });

            }

            //如果呼叫失败，会回调 onInviteFailed。可能的原因有：
            //对方不在线
            //本端网络不通
            //服务器异常
            @Override
            public void onInviteFailed(String channelID, String account, int uid, int i1, String s2) {
                Log.i(TAG, "onInviteFailed  channelID = " + channelID + " account = " + account + " s2: " + s2 + " i1: " + i1);
            }

            @Override
            public void onError(final String s, int i, final String s1) {
                Log.e(TAG, "onError s = " + s + " i = " + i + " s1 = " + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (s.equals("query_user_status")) {
                            Toast.makeText(ExpertVideoActivity.this, s1, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }


            ///该回调返回用户状态查询结果。调用 queryUserStatus 方法时触发此回调。
            @Override
            public void onQueryUserStatusResult(final String name, final String status) {
                Log.i(TAG, "onQueryUserStatusResult name = " + name + " status = " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        int i = 0;
                        for (DoctorVideoBean.DataBean dataBean : mDoctorVideoBean.getData()){
                            if (dataBean.getPhone().equals(name)){
                                 if (status.equals("1")){
                                     dataBean.setOnline(true);
                                     mDoctorVideoBean.getData().add(0,dataBean);
                                     mDoctorVideoBean.getData().remove(i+1);
                                     break;
                                 }else{
                                     dataBean.setOnline(false);
                                     break;
                                 }
                             }
                             i++;
                        }

                        expertVideoAdapter.notifyDataSetChanged();
                    /*    if (status.equals("1")){

                        }else{

                        }*/
                       /* if (status.equals("1")) {
                            channelName = mMyAccount + mSubscriber;
                            mAgoraAPI.channelInviteUser(channelName,mSubscriber, 0);
                        } else if (status.equals("0")) {
                            Toast.makeText(ExpertVideoActivity.this,  " 用户不在线 ", Toast.LENGTH_SHORT).show();
                        }*/
                    }
                });
            }

        });
    }



    @Override
    protected void onResume() {
        super.onResume();
        String username= (String) SpUtils.get(ExpertVideoActivity.this,"s_phone","");
        if (mAgoraAPI.getStatus() != 2) {
            MyApp.the().getmAgoraAPI().login2(getString(R.string.agora_app_id), username, "_no_need_token", 0, "", 5, 1);

        }
        addCallback();

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult requestCode: " + requestCode + " resultCode: " + resultCode);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getStringExtra("result").equals("finish")) {
                finish();
            }
        }
    }
    private void initAgoraEngineAndJoinChannel() {
        mAgoraAPI = MyApp.the().getmAgoraAPI();
    }
}
